package main

import (
	"encoding/json"
	"fmt"
	"github.com/prometheus/common/promlog"
	"gopkg.in/alecthomas/kingpin.v2"
	"log"
	"net/http"
	"os"
	"sync"
	"ubi-helper/src/models"
	"ubi-helper/src/prom"
)

func init() {
}

func main() {
	home := os.Getenv("CONSOLE_MINIO_SERVER")
	fmt.Println("CONSOLE_MINIO_SERVER", home)

	var (
		listenAddress = kingpin.Flag(
			"web.listen-address",
			"Address on which to expose metrics and web interface.",
		).Default(":8888").String()
		staticsPath = kingpin.Flag(
			"web.api-path",
			"Path under which to expose api.",
		).Default("/real-time").String()
	)
	kingpin.Parse()

	logger.Log("apiPath", *staticsPath)

	http.HandleFunc(*staticsPath, staticsHandleFunc)
	logger.Log("msg", "Listening on", "address", *listenAddress)
	server := &http.Server{Addr: *listenAddress}

	if err := server.ListenAndServe(); err != nil {
		log.Fatal(err)
	}
}

func staticsHandleFunc(w http.ResponseWriter, r *http.Request) {
	var (
		wg       sync.WaitGroup
		instance string
		duration string
		isReal   bool
		resp     models.PerformanceResponse
	)
	duration = "1h"
	instance = "117.50.35.145"
	isReal = true
	wg.Add(1)
	go prom.CpuUtilization(instance, duration, isReal, &wg, &resp)
	s, _ := json.Marshal(resp)
	w.Write([]byte(s))
}

var logger = promlog.New(&promlog.Config{})
